package vip.xiaonuo.core.upload;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.common.annotation.CommonLog;
import vip.xiaonuo.common.pojo.CommonResult;
import vip.xiaonuo.core.utils.FileUtil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Api(tags = "文件上传")
@RestController
public class UploadController {

    @Value("${file.img}")
    private String fileImg;

    @ApiOperation("文件上传")
    @CommonLog("文件上传")
    @PostMapping("/uploadFile")
    public CommonResult<Map<String, String>> upload(MultipartFile file) {
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = sdfDate.format(new Date());
        Map<String, String> map = new HashMap<>();
        String filePATH = fileImg + nowDate;
        if (file!=null){
                // 测试MultipartFile接口的各个方法
                String savePath = FileUtil.saveFile(file, filePATH,nowDate);
                if (savePath == null) {
                    return CommonResult.error("文件上传失败");
                }
                map.put("oldFileName",file.getOriginalFilename());
                map.put("newFileName",savePath);
            return CommonResult.data(map);
        }
        return CommonResult.error("未获取到文件");
    }
}
